<?php

namespace app\controller;

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\GuzzleException;
use app\BaseController;
use think\facade\Cache;
use think\captcha\facade\Captcha;
use think\facade\Db;
use think\facade\Session;

class Api extends BaseController
{

    // 获取验证码
    public function getCaptcha()
    {
        return Captcha::create();
    }
    public function loginForSCHUB()
    {
        $data = input('post.');
        if (!captcha_check($data['captcha'] )) {
            return (returnJson(1, '验证码错误'));
        }
        $client = new Client();
        $res = $client->request('POST', 'https://schub.top/api/login', [
            'query' => [
                'user' => $data['email'],
                'pass' => $data['password'],
            ],'verify'=>false
        ]);
        if ($res->getStatusCode() == 200) {
            $body = $res->getBody();
            $body = json_decode($body, true);
            if ($body['code'] == 200) {
                $user = ["uid" => $body['data']['uid'], "username" => $body['data']['user'], "avatar" => $body['data']['head_img']];
                Session('user', $user);
                return (returnJson(msg: "登陆成功"));
            } else {
                return (returnJson(1, msg: $body['msg']));
            }
        } else {
            return (returnJson(1, msg: "连接社区服务器失败,请稍后再试"));
        }
    }
    //登录
    public function login()
    {
        $data = input('post.');
        $captcha =$data['captcha'];
        if ($captcha!=null and !captcha_check($captcha )) {
                return (returnJson(1, '验证码错误'));
        }
        //接口登录
        $user = Db::table('tb_user')->where(['email' => $data['email'], 'password' => hash("sha256","scnet_".$data['password'])])->find();
        if (!$user) {
            return (returnJson(1, msg: "用户名或密码错误"));
        }
        if ($user['state']!=1) {
            return (returnJson(1, msg: "用户已被禁用"));
        }

        if ($captcha!=null) {
            $user = ["uid" => $user["id"], "nickname" => $user["nickname"], "avatar" => $user["avatar"], "admin" => $user["admin"]];
            Session('user', $user);
        }else{
            $user = ['uid'=>$user['id'],'nickname'=>$user['nickname'],'key'=>$user['key'],'token'=>$user['token']];
        }
        return (returnJson(msg: "登陆成功"));
    }

    //登出
    public function logout()
    {
        Session::delete('user');


        return (returnJson(msg: "登出成功"));
    }
    //注册
    public function register()
    {
        $data = input('post.');
        if (Cache::get($data['email'] . "code") != $data['code']) {
            return (returnJson(1, msg: "验证码错误"));
        }
        Cache::delete($data['email'] . "code");
        if (strlen($data['password']) < 6) {
            return (returnJson(1, msg: "密码长度不能小于6位"));
        }
        $user = Db::table('tb_user')->where('email', $data['email'])->find();
        if ($user) {
            return (returnJson(1, msg: "邮箱已经被注册"));
        }
        $user = Db::table('tb_user')->where('nickname', $data['nickname'])->find();
        if ($user) {
            return (returnJson(1, msg: "用户名已经被注册"));
        }

        $res = Db::table('tb_user')->insert(['nickname' => $data['nickname'],'email'=>$data['email'], 'password' => hash("sha256","scnet_".$data['password']), 'token' => md5(uniqid()), 'key'=>md5(uniqid())]);
        if ($res) {
            return (returnJson(msg: "注册成功"));
        } else {
            return (returnJson(1, msg: "注册失败"));
        }
    }
    public function getUserInfo()
    {
        $user = checkLogin();
        return (returnJson(data: ["nickname"=>$user['nickname'],"avatar"=>$user['avatar'],'admin'=>$user['admin']]));
    }
    //获取邮件验证码
    public function getEmailCode()
    {
        $data = input('post.');
        $email = $data['email'];
        checkCaptcha($email);
        $code = rand(100000, 999999);
        $res = sendEmailCode($email, $code);
        if ($res) {
            Cache::set($email."time", time(), 60);
            Cache::set($email."code", $code, 300);
            Session::delete('captcha');
            return (returnJson(msg: "发送成功",data: $code));
        } else {
            return (returnJson(1, msg: "发送失败"));
        }
    }
    //获取短信验证码
    public function getPhoneCode()
    {
        $data = input('post.');
        $phone = $data['phone'];
        checkCaptcha($phone);
        $code = rand(100000, 999999);
        $res = sendSmsCode($phone, $code);
        if ($res) {
            Cache::set($phone."time", time(), 60);
            Cache::set($phone."code", $code, 300);
            Session::delete('captcha');
            return (returnJson(msg: "发送成功"));
        } else {
            return (returnJson(1, msg: "发送失败"));
        }
    }

    //通过邮件验证码找回密码
    public function ForgetForEmail()
    {
        $data = input('post.');
        $email = $data['email'];
        $code = $data['code'];
        $password = $data['password'];
        if (Cache::get($email."code") != $code) {
            return (returnJson(1, msg: "验证码错误"));
        }
        $res = Db::table('tb_user')->where('email', $email)->update(['password' => hash("sha256","scnet_".$password)]);
        if ($res) {
            Cache::delete($email."code");
            return (returnJson(msg: "修改成功"));
        } else {
            return (returnJson(1, msg: "修改失败"));
        }

    }

    //填写图形验证码
    public function VerifyCaptcha()
    {
        try{
        $data = input('post.');
        if (!captcha_check($data['captcha'])) {
            return (returnJson(1, '验证码错误'));
        }
        Session::delete('captcha');
        Session::set ('captcha',time());
        return (returnJson(msg: "验证成功"));
        } catch (\Exception $e) {
            return (returnJson(1, msg: "验证错误"));
        }
    }
}